package app.android.kdictionary.Activity;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import app.android.kdictionary.R;
import app.android.kdictionary.Component.MainResult;
import app.android.kdictionary.R.id;
import app.android.kdictionary.Util.HttpParser;
import app.android.kdictionary.Util.HttpRequester;
import app.android.kdictionary.Util.HttpURLMgr;
import app.android.kdictionary.adapter.WebAdapter;
import app.android.kdictionary.aidl.SearchResultData;
import app.android.kdictionary.aidl.SearchServiceConnection;
import app.android.kdictionary.aidl.WebViewContent;
import app.android.kdictionary.enums.SearchResultType;
import app.android.kdictionary.service.SearchService;

public class HeadwordActivity extends Activity{
	private Activity activity;
	private ListView listView;
	private EditText editText;
	private LinearLayout linearLayout;
	private ImageButton searchButton;
	private TextView sayingTextView;
	private TextView todaySaying;
	
	private WebAdapter mAdapter;
	
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor sharedEditor;
	
	private SearchServiceConnection serviceConnection = null;
	
	private String metaString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
	
	private BackGroundThread backGroundThread;
	
	private boolean noticeFinish = false;
	private WebViewContent content = null;
	private String saying = "가져온 속담 정보가 없습니다.";
	private Thread thread;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.headword);
        
		findView();
		setListener();
		init();
    }
	
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			switch(msg.what) {
				case -1 :
					sayingTextView.setClickable(false);
					todaySaying.setClickable(false);
					sayingTextView.setText(saying);
					break;
				case -3 :
					sayingTextView.setClickable(false);
					todaySaying.setClickable(false);
					sayingTextView.setText("인터넷이 연결되어있지 않습니다.\n연결을 확인해 주세요.");
					break;
				case 2 :
					sayingTextView.setClickable(true);
					todaySaying.setClickable(true);
					sayingTextView.setText(content.getWebViewString());
					break;
			}
		}
	};
    
    private void findView() {
    	editText = (EditText)findViewById(id.search_edit);
    	linearLayout = (LinearLayout)findViewById(id.headword_main);
    	searchButton = (ImageButton)findViewById(id.search_button);
    	sayingTextView = (TextView)findViewById(R.id.saying);
    	todaySaying = (TextView)findViewById(R.id.todaySaying);
    }
    
    private void setListener() {
    	searchButton.setOnClickListener(mSearchClickListener);
    	
    	((TextView)findViewById(R.id.saying)).setOnClickListener(mSayingClickListener);
    	((TextView)findViewById(R.id.todaySaying)).setOnClickListener(mSayingClickListener);
		sayingTextView.setClickable(false);
		todaySaying.setClickable(false);
    }
    
    public OnClickListener mSayingClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if(content != null) {
				sharedEditor.putInt("idx", content.getIdx());
				sharedEditor.commit();
	
				Intent startIntent  = new Intent(getBaseContext(), ResultActivity.class);
				startActivity(startIntent);
			}
		}
    	
    };

    private void init() {
    	sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	sharedEditor = sharedPreferences.edit();
    	activity = this;
    	content = new WebViewContent();
    	content.setIdx(0);
    	content.setWebViewString("");
    	
    	mAdapter = new WebAdapter(getLayoutInflater());
    	
    	Intent intent = new Intent(HeadwordActivity.this, SearchService.class);
    	serviceConnection = new SearchServiceConnection();
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        
        //thread = new Thread(new Saying(this, handler, content, serviceConnection));
        thread = new Thread( new Runnable() {
        	@Override
        	public void run() {
        		ConnectivityManager cm = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        		NetworkInfo wifiNI = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        		NetworkInfo mobileNI = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
        		boolean isWifiAvail = wifiNI.isAvailable();
        		boolean isWifiConn = wifiNI.isConnectedOrConnecting();
        		boolean isMobileAvail = mobileNI.isAvailable();
        		boolean isMobileConn = mobileNI.isConnectedOrConnecting();

        		if(!(isWifiConn || isMobileConn)) {
        			handler.sendEmptyMessage(-3);
        		} else if(!(isWifiAvail || isMobileAvail)) {
        			handler.sendEmptyMessage(-3);
        		} else {
        			int randomNumberOfConsonant = getNumberOfConsonant();
        			String consonant;
        			switch(randomNumberOfConsonant) {
        				case 0 :
        					consonant = "ㄱ";
        					break;
        				case 1 :
        					consonant = "ㄴ";
        					break;
        				case 2 :
        					consonant = "ㄷ";
        					break;
        				case 3 :
        					consonant = "ㄹ";
        					break;
        				case 4 :
        					consonant = "ㅁ";
        					break;
        				case 5 :
        					consonant = "ㅂ";
        					break;
        				case 6 :
        					consonant = "ㅅ";
        					break;
        				case 7 :
        					consonant = "ㅇ";
        					break;
        				case 8 :
        					consonant = "ㅈ";
        					break;
        				case 9 :
        					consonant = "ㅊ";
        					break;
        				case 10 :
        					consonant = "ㅋ";
        					break;
        				case 11 :
        					consonant = "ㅌ";
        					break;
        				case 12 :
        					consonant = "ㅍ";
        					break;
        				case 13 :
        					consonant = "ㅎ";
        					break;
        				default :
        					consonant = "ㄱ";
        			}
        			// web 연결 코드
        			Calendar today = Calendar.getInstance();
        			int value = today.get(Calendar.YEAR)*100000 + today.get(Calendar.MONTH)*100 + today.get(Calendar.DAY_OF_MONTH);
        			
                	HttpURLMgr hum = new HttpURLMgr();
                	HttpRequester hr = new HttpRequester();
                	HttpParser hp = new HttpParser();
                	String amount;
                	int page = 1;
                	int contentNum = 0;
                	int contentNumInPage = 0;
                	
                	ArrayList<WebViewContent> list = new ArrayList<WebViewContent>();

                	try {
                		hum.setSectionSearchParams("", "1", consonant, 2);
                		amount = hp.getProverbCategoryAmount(hr.request(hum.getSectionSearchURL(2), "POST", hum.getParams()));
                		contentNum = value%Integer.parseInt(amount);
                		page = contentNum/10 + 1;
                		contentNumInPage = contentNum%10;
                		
                		hum.setPage(page);
                		hp.parseSectionList(hr.request(hum.getSectionSearchURL(2), "POST", hum.getParams()), list);
                		String proverbStr = list.get(contentNumInPage).getWebViewString();
                		proverbStr = proverbStr.substring(proverbStr.indexOf("<strong>")+8, proverbStr.indexOf("</strong>"));
                		proverbStr = proverbStr.substring(proverbStr.indexOf(">")+1, proverbStr.lastIndexOf("<"));
                		content.setIdx(list.get(contentNumInPage).getIdx());
                		content.setWebViewString(proverbStr);
                		Log.i("<in headActivity>",(content.getWebViewString()));
                	} catch (Exception e) {
                		content = null;
                		e.printStackTrace();
                	}
    				if(content == null) {
    					handler.sendEmptyMessage(-1);
    				} else {
    					handler.sendEmptyMessage(2);		
    				}
        			
        		}
        	}
        });
		thread.start();

    }
    
	public int getNumberOfConsonant() {
		Calendar today = Calendar.getInstance();
		int value = today.get(Calendar.YEAR) + today.get(Calendar.MONTH) + today.get(Calendar.DAY_OF_MONTH);
		int numberOfVowel = 14;
		return (value % numberOfVowel);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "프로그램정보");
		return (super.onCreateOptionsMenu(menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return (applyMenuChoice(item) || super.onContextItemSelected(item));
	}
	
	private boolean applyMenuChoice(MenuItem item) {
		switch(item.getItemId()) {
			case Menu.FIRST+1 :
				this.informationButtonClicked();
				return true;
		}
		return false;
	}
	
	private void informationButtonClicked() {
		startActivity(new Intent(HeadwordActivity.this, ProgramInfoActivity.class));
	}
	
	@Override
	public void onRestart() {
		this.noticeFinish = false;
		super.onRestart();
	}
	
	@Override
	public void onBackPressed() {
		if(this.noticeFinish == false) {
			Toast.makeText(this, "'뒤로' 버튼을 한번 더 누르면 종료합니다.", Toast.LENGTH_SHORT).show();
			this.noticeFinish = true;
		} else {
			super.onBackPressed();
			finish();
		}
	}
	
	
	
    private OnClickListener mSearchClickListener = new OnClickListener() {
        public void onClick(View v) {
			// keyboard remove
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    		
			// adapter clear
			mAdapter.clear();
    		
        	if( backGroundThread == null ) {
        		backGroundThread = (BackGroundThread) new BackGroundThread();
        		backGroundThread.execute();
        	}
        	else {
        		switch(backGroundThread.getStatus()) {
	        		case PENDING :
	        		case RUNNING :
	        			backGroundThread.cancel(true);
	        		case FINISHED :
	        			backGroundThread = (BackGroundThread) new BackGroundThread();
	        			backGroundThread.execute();
	        			break;
        		}	
        	}
        }
    };
    
	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
			switch( mAdapter.getItem(position).getType() ) {
				case ADD :
		        	if( backGroundThread == null ) {
		        		backGroundThread = (BackGroundThread) new BackGroundThread();
		        		backGroundThread.execute();
		        	}
		        	else {
		        		switch(backGroundThread.getStatus()) {
			        		case PENDING :
			        		case RUNNING :
			        			backGroundThread.cancel(true);
			        		case FINISHED :
			        			backGroundThread = (BackGroundThread) new BackGroundThread();
			        			backGroundThread.execute();
			        			break;
		        		}	
		        	}
					break;
					
				case RESULT :
					sharedEditor.putInt("idx", mAdapter.getItem(position).getIdx());
					sharedEditor.commit();

					Intent startIntent  = new Intent(getBaseContext(), ResultActivity.class);
					startActivity(startIntent);
					break;
					
				case NOTFOUND :
					break;
					
				case PROGRESS :
					break;
			}
		}
	};
	
    // AsyncTask클래스는 항상 Subclassing 해서 사용 해야 함.
    // 사용 자료형은
    // background 작업에 사용할 data의 자료형: String 형
    // background 작업 진행 표시를 위해 사용할 인자: Integer형
    // background 작업의 결과를 표현할 자료형: Long
	private class BackGroundThread extends AsyncTask<String, Integer, Integer> {
		private SearchResultData searchResultData;
		
    	// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
    	// 작업 시작을 UI에 표현하거나
    	// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
		@Override
		protected void onPreExecute() {
    		// remove
        	linearLayout.removeAllViewsInLayout();
        	
        	// mainResult create & add
    		MainResult mainResult = new MainResult(getBaseContext());
    		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F);
    		linearLayout.addView(mainResult, lp);
    		
    		// set listview
    		listView = (ListView)findViewById(id.search_result_list);	
    		listView.setAdapter(mAdapter);
    		listView.setOnItemClickListener(mItemClickListener);
        	
    		mAdapter.addItem(new WebViewContent(-1, "", SearchResultType.PROGRESS) );
    		
        	super.onPreExecute();
		}

		// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback 
		@Override
    	protected Integer doInBackground(String... strData) {
        	try {
        		searchResultData = serviceConnection.getmService().simpleSearch(editText.getText().toString());
			} catch (RemoteException e) {
				e.printStackTrace();
			}
    		
    		return 1;
    	}
    	
    	// onInBackground(...)에서 publishProgress(...)를 사용하면
    	// 자동 호출되는 callback으로 이곳에서 ProgressBar를 증가 시키고, 
		// text 정보를 update하는 등의 background 작업 진행 상황을 UI에 표현함.
    	@Override
    	protected void onProgressUpdate(Integer... progress) {
    	}
    	
    	// onInBackground(...)가 완료되면 자동으로 실행되는 callback
    	@Override
    	protected void onPostExecute(Integer result) {
    		mAdapter.removeLastItem();
    		
    		ArrayList<WebViewContent> list = searchResultData.getWebViewContentList();    		
    		int size = searchResultData.getWebViewSize();
    		
    		if(size==0) {
    			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.not_found_string), SearchResultType.NOTFOUND));
    		}
    		else {
        		// mAdapter addItems
        		mAdapter.addItems(list);
        		
            	if( mAdapter.getCount()<size ) {
        			mAdapter.addItem(new WebViewContent(-1, metaString+getString(R.string.more_string), SearchResultType.ADD));
            	}
    		}
    	}
    	
    	// AsyncTask.cancel(boolean) 메소드가 true 인자로 실행되면 호출되는 콜백.
    	// background 작업이 취소될때 꼭 해야될 작업은  여기에 구현.
    	@Override
		protected void onCancelled() {
			super.onCancelled();
		}  
	}
}